{% extends 'basic_app/master.html' %}
{% block tag_left %}
    {% include 'mytk_app/tag_left_user.html' %}
{% endblock %}
{% block title %}
    <title>ORATK</title>
{% endblock %}
{% block userinfo %}
    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
        <form name="Form" id="ajax_form_sumit" role="search" action="/oratk_app/oratk_most_box_ajax"
              onsubmit="return validateForm()"
              target="_blank" method="POST">
            <h3 class="page-header">活动会话信息</h3>
            <div class="navbar-form navbar-left">
                &nbsp 选择实例: &nbsp
                {#                <select class="form-control" name="conn_string" id="conn_string">#}
                <select class="selectpicker show-tick " style="width:450px" data-live-search="true" name="conn_string"
                        id="conn_string">

                    <option id="def">--请选择实例名--</option>
                    <optgroup label="total:{{ instanceinfo_result_total }}">
                        {% for i in instanceinfo_result %}
                            <option
                                    data-content="
                <div>{{ i.id }}.{{ i.dbname }}</div>
                <div style='padding-left: 15px;'><small>{{ i.conn_string }}</small></div>
            "
                                    value="{{ i.id }}.{{ i.dbname }}={{ i.conn_string }}">
                            </option>
                        {% endfor %}
                    </optgroup>
                </select>
                &nbsp
                <button type="button" data-loading-text="Loading..." class="btn btn-default btn-primary" id="btSearch">
                    查询(本页展示）
                </button>
                <button type="submit" class="btn btn-default btn-primary" id="btSearch_new">查询(新页展示）</button>
                <div>&nbsp</div>
                <div>
                    <div class="checkbox-inline">
                        <label>
                            <input type="checkbox" checked readonly id="box_session_event" name="box_val"
                                   value="event_overview"> event_overview
                        </label>
                    </div>
                    <div class="checkbox-inline">
                        <label>
                            <input type="checkbox" checked readonly name="box_val" value="event_stats">
                            event_stats
                        </label>
                    </div>

                    <div class="checkbox-inline">
                        <label>
                            <input type="checkbox" id="box_breaker_info" name="box_val"
                                   value="lock"> lock
                        </label>
                    </div>
                    <div class="checkbox-inline">
                        <label>
                            <input type="checkbox" id="box_breaker_info" name="box_val"
                                   value="session_detail_lock"> session_detail_lock
                        </label>
                    </div>
                </div>
                <div>&nbsp</div>
                <div id="tab_detail"></div>
            </div>
        </form>
    </div>

    {#    显示会话详情模态框#}
    <div class="modal fade" id="myModal_session_detail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content" style="width:1000px" id="docModalContent">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    {#                    <h4 class="modal-title" id="myModalLabel">会话详情: {{ session_info }}</h4>#}
                    <h4 class="modal-title" id="myModalLabel">
                        会话详情: &nbsp <span id="session_info" style="color: green">{{ session_info }}</span>
                        &emsp;&emsp;
                        动作:&nbsp <a href="javascript:void(0);" id="kill_session_link"
                                    style="color: red"> kill_current_session {{ session_info }}</a>
                    </h4>

                </div>
                <span>&nbsp</span>
                <div class="col-sm-12 modal-body" style="float: none; " id="tab_detail_session_detail">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>




{% endblock %}

{% block script %}
    <script>
        //新页展示按钮执行前判断输入框是否有空值
        function validateForm() {
            var select_conn = $('#conn_string').find("option:checked").attr("id")
            if (select_conn == 'def') {
                alert('请选择实例')
                return false;
            }
        }

        //当点击"查询(本页展示)时，输入框值检查及ajax异步调用"
        $('#btSearch').click(function () {
            var select_conn = $('#conn_string').find("option:checked").attr("id")
            if (select_conn == 'def') {
                alert('请选择实例')
                return;
            }
            //发送ajax请求
            let data = $('#ajax_form_sumit').serialize();
            $.ajax({
                type: "POST",
                data: data,
                url: "/oratk_app/oratk_most_box_ajax", //后台处理函数的url
                cache: false,
                dataType: "html",
                success: function (result) {
                    $("#tab_detail").html(result);
                },
                beforeSend: function () {
                    // $('#loadingModal').modal({backdrop: 'static', keyboard: false});
                    showLoading()
                    $('#btSearch').button('loading')
                },
                complete: function () {
                    //$('#loadingModal').modal('hide');
                    hideLoading()
                    $('#btSearch').button('reset')
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    showconnectionAlert(XMLHttpRequest, textStatus, errorThrown)
                }

            })
        })

    </script>
    {#event_overview#}

    <script>
        function confirmKillSession(sessionValue) {
            let title = `确定要终止此会话吗？(${sessionValue})`;
            var result = '此操作不可撤销';
            var iconType = 'warning';
            let iscancelButton = true;

            // 调用公共方法
            showAlert(title, result, iconType, iscancelButton, function () {
                exec_kill_session_command(sessionValue);  // 会话终止操作
            })
        }

        {# kill session #}

        function exec_kill_session_command(val) {
            var conn_string = $('#conn_string').val();
            var session_info = val;
            $.ajax({
                type: "POST",
                url: "/oratk_app/oratk_most_sessionevent_session_ajax", //后台处理函数的url
                data: {
                    'conn_string': conn_string,
                    'session_info': session_info,
                    'request_tag': 'kill_session'
                },
                cache: false,
                dataType: "html",
                success: function (result) {
                    // 判断 result 是否以 "ERROR" 开头
                    var iconType = result.startsWith("Error") ? "error" : "success";
                    var title = iconType === "error" ? "执行失败" : "执行成功"
                    var result = result
                    let iscancelButton = false;
                    // 调用公共方法弹窗
                    showAlert(title, result, iconType, iscancelButton);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    showconnectionAlert(XMLHttpRequest, textStatus, errorThrown)
                }
            })
        }


        {#    show sesson detail #}

        function show_kill_session_detail(val) {
            var conn_string = $('#conn_string').val();
            var session_info = val;
            $.ajax({
                type: "POST",
                url: "/oratk_app/oratk_most_sessionevent_session_ajax", //后台处理函数的url
                data: {
                    'conn_string': conn_string,
                    'session_info': session_info,
                    'request_tag': 'show_session_detail'
                },
                cache: false,
                dataType: "html",
                success: function (result) {
                    {#会话详情赋值#}
                    $('#session_info').text(session_info);
                    {#onclick中session_info赋值#}
                    // 更新 `onclick` 函数调用
                    $('#kill_session_link').attr('onclick', 'confirmKillSession("' + session_info + '")');

                    $("#tab_detail_session_detail").html(result);
                    //调用模态框
                    $('#myModal_session_detail').modal('show')
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    showconnectionAlert(XMLHttpRequest, textStatus, errorThrown)
                }
            })
        }


        {#    show sql plan#}

        function show_sql_explain(val) {
            var conn_string = $('#conn_string').val();
            var sql_id = val;
            $.ajax({
                type: "POST",
                url: "/oratk_app/oratk_most_box_ajax", //后台处理函数的url
                data: {
                    'conn_string': conn_string,
                    'sql_id': sql_id,
                    'request_tag': 'event_overview_sql_explain'
                },
                cache: false,
                dataType: "html",
                success: function (result) {
                    var newWindow = window.open("", "_blank"); // 打开新窗口
                    newWindow.document.write(result);  // 将后端返回的 HTML 内容写入
                    newWindow.document.close();  // 确保浏览器正确渲染页面
                    {#// 监听新窗口的 `DOMContentLoaded` 事件，等 HTML 加载完成再执行表格转换#}
                    {#newWindow.addEventListener("DOMContentLoaded", function () {#}
                    {#    convertTableToText(newWindow);});#}

                    // 等待新窗口加载完成后执行表格转换
                    newWindow.onload = function () {
                        convertTableToText(newWindow);
                    };

                }
            })
        }

        function convertTableToText(win) {
            const tables = win.document.querySelectorAll("#tab_id_sql_xp_cursor, #tab_id_sql_xp_awr"); // 在新窗口查找表格
            tables.forEach(table => {
                const rows = table.querySelectorAll("tr");
                let textData = "";

                rows.forEach(row => {
                    const cells = row.querySelectorAll("td, th");
                    const rowText = Array.from(cells).map(cell => cell.innerText.trim()).join(", ");
                    if (rowText) { // 跳过空行
                        textData += rowText + "\n";
                    }
                });

                const textContainer = win.document.createElement("pre");
                textContainer.style.width = "100%";
                textContainer.style.overflowX = "auto";
                textContainer.style.whiteSpace = "pre-wrap";
                textContainer.textContent = textData.trim();
                table.replaceWith(textContainer);
            });
        }
    </script>
{% endblock %}

